package com.didispace.web;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.didispace.domain.User;



 
public class testController
{
	Logger logger = LoggerFactory.getLogger(testController.class);

	public String createPost(String url, String params, HttpClientContext context) throws Exception
	{
		// UrlEncodedFormEntity entity = new UrlEncodedFormEntity   
		HttpEntity entity = new StringEntity(params, "UTF-8");
		HttpPost post = new HttpPost(url);
		post.setEntity(entity);
		CloseableHttpClient httpClient = HttpClients.createSystem();

		CloseableHttpResponse respons = httpClient.execute(post, context);
		int responseCode = respons.getStatusLine().getStatusCode();
		if(responseCode == 200)
		{
			String resopnseEntity = EntityUtils.toString(respons.getEntity());
			return resopnseEntity;
		}
		if(responseCode == 302)
		{
			String resopnseEntity = EntityUtils.toString(respons.getEntity());
			return resopnseEntity;
		}

		return null;
	}   

	public String createGet(String url, HttpClientContext context) throws Exception
	{
		HttpGet get = new HttpGet(url);
		CloseableHttpClient httpClient = HttpClients.createSystem();
		CloseableHttpResponse respons = httpClient.execute(get, context);
		int responseCode = respons.getStatusLine().getStatusCode();
		if(responseCode == 200) { return EntityUtils.toString(respons.getEntity()); }

		this.logger.warn(respons.getStatusLine().getReasonPhrase());

		return null;
	}
	 public static void main(String[] args) throws Exception {
		testController p1 = new testController();
		User user = new User();
		user.setAge(22);
		user.setId(1l);
		user.setName("哈哈zzzzzz");
		
		p1.createPost("http://localhost:8080/users/",JSONObject.toJSONString(user),new HttpClientContext());
	}
}
